import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-06-18
 * Time: 20:36
 */
public class BufferedReaderWriter {
    //使用BufferedReader和BufferedWriter复制文本文件
    public static void main(String[] args) throws IOException {
        File file = new File("test.txt");
        File file1 = new File("test2.txt");
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file1));

        String str;
        while ((str = bufferedReader.readLine()) != null) {
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            bufferedWriter.flush();//刷新,每当调用此方法时,就会主动地将内存中的数据写出到磁盘文件中
        }
        bufferedReader.close();
        bufferedWriter.close();
    }
    //使用BufferedReader系那个文件中的内容显示在控制台上
    public static void main1(String[] args) {
        BufferedReader bufferedReader = null;
        try {
            File file = new File("test.txt");
            bufferedReader = new BufferedReader(new FileReader(file));

            //读取的过程
//            //法1
//            char[] cBuffer = new char[1024];
//            int len;//记录每次读入到数组的个数
//            while ((len = bufferedReader.read(cBuffer)) != -1) {
//                //方法1
//    //            for (int i = 0; i < len; i++) {
//    //                System.out.print(cBuffer[i]);
//    //            }
//                //方法二
//                String str = new String(cBuffer, 0, len);
//                System.out.print(str);
//            }
            //法2
            String data;
            //每次读取一行,返回的字符串中不包含\n
            while ((data = bufferedReader.readLine()) != null) {
                System.out.println(data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
